const db = require('../config/db')

/**
 * 内容列表接口逻辑
 */
exports.contentList = (req, res) => {
    // 获取前端的参数
    let { Search, page, size } = req.query;
    page = (page - 1) * size;
    let pageSql = 'select * from cms_content where del=0 '
     // 查询内容总数的sql
    let totalSql = 'select count(*) as total from cms_content where del=0'
    // 查询内容列表sql
    if (Search == null) {
        pageSql = pageSql + 'limit ?, ?'
        argument = [Number(page), Number(size)]
    } else {
        pageSql = pageSql + ' and name like ? limit ?, ?'
        argument = ["%" +Search + "%", Number(page), Number(size)]
        totalSql = totalSql + " and name like ?"
    }

   

    db.query(pageSql, argument, (err, resPage) => {

        if (err) {
            return res.send({ code: 1, message: err.message });
        }
        db.query(totalSql, "%" + Search + "%" ,(err, resTotal) => {
            if (err) {
                return res.send({ code: 1, message: err.message });
            }
            res.send({
                code: 0,
                data:{
                    list:resPage,
                    total:resTotal
                }
            })
        })
    })
}

/**
 * 内容添加接口
 * 必传 
 * 返回
 * 状态码
 */
exports.addContentList = (req, res) => {
    let { name, orderby, author, contents, cms_columnId} = req.body;
    console.log(name, orderby, author, contents, cms_columnId);
    
    // 添加校验
    if (!name || !orderby || !author || !contents) {
        return res.send({ code: 1, message: '名字,排序,作者，内容均不能为空！' });
    };
    // 内容信息插入数据库
    const userInsertSql = 'insert into cms_content (name, orderby, author, content, cms_columnId) value ( ?, ?, ?, ?, ?)'
    db.query(userInsertSql, [name, orderby, author, contents, cms_columnId], (err, result) => {
        if (err) {
            return res.send({ code: 1, message: err.message });
        };
        res.send({
            code: 0,
            message: '添加成功',
        })
    })
};


/**
 * 修改内容接口
 */
exports.updateContentListById = (req, res) => {
    let { id, name, orderby, author, contents, cms_columnId } = req.query;
    let sql = 'update cms_content set  name = ?, orderby = ?, author = ? , content = ?, cms_columnId = ? where id = ?'
    db.query(sql, [name, orderby, author, contents, cms_columnId, id], (err, results) => {
        if (err) {
            return res.send({ code: 1, message: err.message });
        }
        res.send({ code: 0, message: '修改成功' });
    })
}

// 删除栏目接口
exports.deleteContentListById = (req, res) => {
    let { id } = req.query;
    let sql = 'update cms_content set del = 1 where id = ?'
    db.query(sql, id, (err, result) => {
        if (err) {
            return res.send({ code: 1, message: err.message });
        }
        res.send({ code: 0, message: '删除成功' })

    })
}